package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) throws IOException {

        if(ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            return ResultVO.failed("文件不能为空");
        }
        if(!imageProperties.getTypes().contains(pic.getContentType())) {
            String types=imageProperties.getTypes().stream()
                    .map(type->type.substring(type.lastIndexOf("/")+1))
                    .collect(Collectors.joining(","));
            return ResultVO.failed("只支持"+types+"类型的图片");
        }
        //新文件名称
        String fileName = IdUtil.simpleUUID()+"."+ FileNameUtil.getSuffix(pic.getOriginalFilename());
        //创建目录
        File uploadDir=new File(imageProperties.getUploadDir());
        if(!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        //目标文件
        File destFile=new File(uploadDir,fileName);
        pic.transferTo(destFile);
        String path = imageProperties.getMapping().endsWith("/") ?
                imageProperties.getMapping()+fileName:
                imageProperties.getMapping()+"/"+fileName;
        return ResultVO.success(path);
    }
}
